package com.charon.common.config;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeSet;

import com.charon.common.util.PropertiesLoader;

/**
  *@ClassName: Global
  *@Description: 全局配置类，获取配置文件中的数据,优先加载charon.properties文件
  *@Author: Moment
  *@Date: 2018/7/7 0007 19:57
  *@Version: 1.0
  */
public class Global {
    /**
     * 保存全局属性值
     */
    private static Map<String, String> map = new HashMap<String,String>();

    private static TreeSet<String> pathTS=new TreeSet<String>();
    
    /**
     * 配置文件加载对象
     */
    private static PropertiesLoader loader = new PropertiesLoader("charon.properties","music.properties");

    /**
     * 获取配置 会优先加载Map中存在的值
     */
    public static String getConfig(String key) {
        String value = map.get(key);
        if (value == null) {
            value = loader.getProperty(key);
            map.put(key, value != null ? value :"");
        }
        return value;
    }
    
    public Global(String... path){
    	pathTS.add("charon.properties");
    	pathTS.add("music.properties");
    	for(String p:path){
    		pathTS.add(p);
    	}
    	loader = new PropertiesLoader(pathTS.toArray(new String[]{}));
    	loader.initAllConfig(map);
    }
    public String getAttribute(String key){
    	String value = map.get(key);
        if (value == null) {
            value = loader.getProperty(key);
            map.put(key, value != null ? value :"");
        }
        return value;
    }
    
    public HashMap<String,String> getConfByKeyReg(String reg){
    	Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
    	HashMap<String,String> map=new HashMap<String,String>();
    	while(iterator.hasNext()){
    		Entry<String, String> next = iterator.next();
    		String key=next.getKey();
    		if(key.indexOf(reg)>-1){
    			map.put(key, next.getValue());
    		}
    	}
    	return map;
    }

}
